//
//  SmsCodeController.m
//  FbeeAPP
//
//  Created by dev-m on 2018/3/5.
//  Copyright © 2018年 mohao. All rights reserved.
//

#import "SmsCodeController.h"
#import "FbeeCommitBtn.h"
#import "FbeeInputView.h"
#import "TTCountDownButton.h"

@interface SmsCodeController ()
{
    NSString *phoneNum;
    NSString *picCode;
    NSString *areaCode;
    
    UIScrollView *mainView;
    UIButton *backBtn;
    FbeeInputView *smsCodeF;
    FbeeCommitBtn *commit;
    TTCountDownButton *countBtn;
    
}

@end

@implementation SmsCodeController

-(void)dealloc
{
    NSLog(@"SmsCodeController dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(instancetype)initWithPhone:(NSString *)phone picCode:(NSString *)pic area:(NSString *)area
{
    self = [super init];
    
    if (self) {
        phoneNum = phone;
        picCode = pic;
        areaCode = area;
        
    }
    
    return self;
}

//-(void)viewDidAppear:(BOOL)animated
//{
//    [smsCodeF becomeFirstResponder];
//}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationView.hidden = YES;
    
    // 添加观察
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self buildView];
    
}

-(void)buildView
{

    
    mainView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, IPHONEHEIGHT)];
    mainView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mainView];

    
    smsCodeF = [[FbeeInputView alloc] initWithText:NSLocalizedString(@"textLoginSmsCode", nil)];
    smsCodeF.centerX = IPHONEWIDTH/2;
    smsCodeF.top = 238.5;
    [smsCodeF setKeyboardType:UIKeyboardTypeASCIICapable];
    [mainView addSubview:smsCodeF];
    
    commit = [[FbeeCommitBtn alloc] initWithTitle:NSLocalizedString(@"mConfirm", nil)];
    commit.centerX = IPHONEWIDTH/2;
    commit.top = smsCodeF.bottom + 65;
    [commit onClick:^{
        [self quickLogin];
    
    }];
    [mainView addSubview:commit];
    
    
    [self.largeTitle setTitle:NSLocalizedString(@"tNavUCenterSmsCode", nil)];
    
    backBtn = [UIButton makeButton:^(TTButtonExtend *make) {
        make.setFrame(CGRectMake(0, StatusHeight, 60, 44));
        make.addImage([UIImage imageNamed:@"nav_back"],UIControlStateNormal);
        make.addTarget(self,@selector(navback));
        [self.view addSubview:make];
    }];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(13.5, 16, 13.5, 27);
    
    @weakify(smsCodeF)
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id sender) {
        @strongify(smsCodeF)
        [smsCodeF resignFirstResponder];
    }];
    [mainView addGestureRecognizer:tap];
    
    [self bringTitleToFront];
    
    UILabel *info = [UILabel makeLabel:^(TTLabelExtend *make) {
        NSString *info = [NSString stringWithFormat:@"%@ +%@ %@",NSLocalizedString(@"textSmsSend", nil),areaCode,phoneNum];
        make.addText(info);
        make.addTextColor(FBEE_COLOR_INFO).addFont([UIFont systemFontOfSize:16.0f]);
        make.setFrame(CGRectMake(16, self.largeTitle.bottom + 10, 0, 0));
        [make sizeToFit];
        make.height = 18;
        [self.view addSubview:make];
    }];
    
    UIButton *edit = [UIButton makeButton:^(TTButtonExtend *make) {
        make.addTitle(NSLocalizedString(@"mEdit", nil)).addTitleColor(UIColorFromRGB(0x20E4FE),UIControlStateNormal);
        make.addFont([UIFont systemFontOfSize:16]);
        make.setFrame(CGRectMake(0, 0, 50, 40));
        make.left = info.right;
        make.centerY = info.centerY;
        make.addTarget(self,@selector(navback));
        [self.view addSubview:make];
    }];
    
    //获取短信验证码
    countBtn = [TTCountDownButton buttonWithType:UIButtonTypeCustom];
    __weak id weakSelf = self;
    [countBtn setUpWithFrame:CGRectMake(0, 0, 70, 35) defaultCount:60 defaultTitle:@"59" countDownTitle:@"s" tapped:^{
        [weakSelf getSmsCode];
    }];
    countBtn.centerY = smsCodeF.height/2.0f;
    countBtn.right = smsCodeF.width - 12;
    [smsCodeF addSubview:countBtn];
    [countBtn timerBegin];
    [countBtn setDefaultTitle:NSLocalizedString(@"mSendCode", nil)];

    smsCodeF.textF.width = countBtn.left - smsCodeF.textF.left;
    
    if ([KeyBoardManager sharedManager].keyBoardShow) {
        float sub = commit.bottom - (IPHONEHEIGHT - [KeyBoardManager sharedManager].keyHeight);
        if (sub > 0) {
            [mainView setContentOffset:CGPointMake(0, sub) animated:YES];
        }
    }
}

- (void)keyboardWillShow:(NSNotification *)notification {
    float sub = commit.bottom - (IPHONEHEIGHT - [KeyBoardManager sharedManager].keyHeight);
    if (sub > 0) {
        [mainView setContentOffset:CGPointMake(0, sub) animated:YES];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification {
    if (mainView.contentOffset.y>0) {
        [mainView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    
}

#pragma mark - getData

-(void)getSmsCode
{
    NSString *url = [NSString stringWithFormat:@"%@?mobile=%@&code=%@&area=%@",SmsCode_URL,phoneNum,picCode,areaCode];
    [self get:url code:SmsCode_URL_Code];
    [countBtn timerBegin];
}

-(void)quickLogin
{
    if ([NSString isEmptyString:[smsCodeF getText]]) {
        [NoticePopHelper showNoticeText:NSLocalizedString(@"textCheckCodeInfo", nil)];
        return;
    }
    
    [self post:login_URL param:@{@"mobile":phoneNum,@"code":[smsCodeF getText],@"area":areaCode} code:login_URL_Code];
    
}

#pragma mark - request

-(void)requestSuccess:(id)data code:(NSInteger)code
{
    //短信发送成功
    if (code == SmsCode_URL_Code) {
    }
    
    //登录成功
    if (code == login_URL_Code) {
        
        NSString *token = SafeGetStringValue([SafeGetDictionaryValue([data objectForKey:@"user"]) objectForKey:@"token"]);
        NSString *uid = SafeGetStringValue([SafeGetDictionaryValue([data objectForKey:@"user"]) objectForKey:@"id"]);
        NSString *mobile = SafeGetStringValue([SafeGetDictionaryValue([data objectForKey:@"user"]) objectForKey:@"mobile"]);
        NSString *area = SafeGetStringValue([SafeGetDictionaryValue([data objectForKey:@"user"]) objectForKey:@"area"]);
        NSString *nickname = SafeGetStringValue([SafeGetDictionaryValue([data objectForKey:@"user"]) objectForKey:@"nickname"]);
        NSString *topicCount = SafeGetStringValue([SafeGetDictionaryValue([data objectForKey:@"user"]) objectForKey:@"topicCount"]);
        NSString *walletAddress = SafeGetStringValue([SafeGetDictionaryValue([data objectForKey:@"user"]) objectForKey:@"walletAddress"]);
        
        bool isNew =  SafeGetBOOLValue([SafeGetDictionaryValue([data objectForKey:@"user"]) objectForKey:@"newUser"]);
        
        [[UserInfoManager sharedManager] setLoginInfoByToken:token userId:uid];
        [UserInfoManager sharedManager].mobile = mobile;
        [UserInfoManager sharedManager].areaCode = area;
        [UserInfoManager sharedManager].nickName = nickname;
        [UserInfoManager sharedManager].walletAddr = walletAddress;
        [UserInfoManager sharedManager].topicCount = topicCount;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_LoginSuccess object:nil];
        
        if (isNew) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[JumpManager sharedManager] jumpToMyNickNameEx];
            });
        }
        
        
    }
    
}

-(void)requestLogicError:(id)data code:(NSInteger)code
{
    [super requestLogicError:data code:code];
}

-(void)requestFailure:(NSError *)error code:(NSInteger)code
{
    
}


@end
